package nsga.comparison.util;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import foundation.dbUtil.DBException;
import foundation.dbUtil.DBUtil;

/**
 * 
 * @author nyc
 *
 */
public class DBDAO {

	protected String dbCfgFileName = "";
	protected DBUtil dbUtil = null;

	public DBDAO() {
		dbCfgFileName = "src/foundation/dbUtil/dbConf.properties";
		dbUtil = DBUtil.getInstance(dbCfgFileName);
	}

	public DBDAO(String dbCfgFileName) {
		this.dbCfgFileName = dbCfgFileName;
		dbUtil = DBUtil.getInstance(dbCfgFileName);
	}
	
	public synchronized int execute(String sqlTxt) throws SQLException, DBException {
		PreparedStatement pStmt = dbUtil.getPrepStmt(sqlTxt);
		int rlt=pStmt.executeUpdate();
		pStmt.close();
		return rlt;
	}
	
	/**
	 * 从数据库中读取最后一代的目标值
	 * @param runID
	 * @param genID
	 * @return
	 */
	public ArrayList<ArrayList<Float>> getObjVals(String runID,String genID){
		ArrayList<ArrayList<Float>> onceObjvals = new ArrayList<ArrayList<Float>>();
		ArrayList<Float> objVals  = null;
		
//		String sqlTxt = "SELECT * FROM t_run where runID =  '"+runID+"' and genID='"+genID+"'" ;
		String sqlTxt = "SELECT * FROM t_run where runID =  '"+runID+"'" ;
			
		PreparedStatement pStmt = null;
		ResultSet rs = null;
		float restVal = 0f;
//		float reltVal = 0f;
		float costVal = 0f;
		try {
			pStmt = dbUtil.getPrepStmt(sqlTxt);
		
		rs = pStmt.executeQuery();
		while(rs.next()){
//		for(int i=0;i<6000;i++){
			objVals = new ArrayList<Float>();
//			rs.next();
			restVal = rs.getFloat("RestValue");
//			reltVal = rs.getFloat("ReltValue");
			costVal = rs.getFloat("costValue");
			objVals.add(restVal);
//			objVals.add(1-reltVal);
			objVals.add(costVal);
			onceObjvals.add(objVals);
		}
		} catch (DBException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return onceObjvals;
	}
		
	public synchronized void  closeDBCon(){
		if(dbUtil!=null){
			try {
				dbUtil.closeConn();
			} catch (DBException e) {
				e.printStackTrace();
			}
		}
	}
}
